package com.osgix.common.utils.xmlUtil.impl;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.apache.log4j.Logger;

import com.osgix.common.utils.xmlUtil.IXmlGenerator;

public class XmlGeneratorImpl<T> implements IXmlGenerator<T> {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(XmlGeneratorImpl.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.thuni.tools.xmlUtil.iface.IXmlGenerator#generateXml(java.lang.Object)
	 */
	public String generateXml(T instance) {
		JAXBContext context;
		StringWriter sw = new StringWriter();
		try {
			context = JAXBContext.newInstance(instance.getClass());
			Marshaller m = context.createMarshaller();
			m.marshal(instance, sw);
			m.setProperty("jaxb.encoding", "utf-8");// 设置编码
			m.setProperty("jaxb.formatted.output", true);// 设置xml是否格式化
			String xmlStr = sw.getBuffer().toString();
			if (logger.isDebugEnabled()) {
				logger.debug(xmlStr);
			}
			return xmlStr;
		} catch (JAXBException e) {
			e.printStackTrace();
			return null;
		}
	}
}
